<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="search_form.title" placeholder="公告标题" style="width: 300px;" clearable />
      <el-select v-model="search_form.type" placeholder="公告状态" style="width: 150px;">
        <el-option label="全部" value="" />
        <el-option label="发布" value="1" />
        <el-option label="草稿" value="0" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handle_search">搜索</el-button>
      <el-button @click="handle_reset">重置</el-button>
      <el-button type="success" icon="el-icon-plus" @click="handle_add">新增公告</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="announcement_list"
      style="width: 100%"
      border
    >
 
          <el-table-column
      type="index"
       label="公告ID" 
      width="80">
    </el-table-column>
    <el-table-column prop="title" label="公告标题" min-width="200">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 1 ? 'success' : 'info'" size="small" style="margin-right: 8px;">
            {{ scope.row.type === 1 ? '已发布' : '草稿' }}
          </el-tag>
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="发布人" />
      <!-- 保留原有的publisher_id作为隐藏列，方便后续处理 -->
      <el-table-column prop="publisher_id" label="发布人ID" width="80" align="center" v-if="false" />
    <el-table-column prop="publish_time" label="发布时间" />
    <el-table-column prop="created" label="创建时间" />
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handle_view(scope.row)">查看</el-button>
          <el-button type="info" size="small" @click="handle_edit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handle_delete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="page_size"
        :current-page="page_num"
        @current-change="handle_current_change"
        @size-change="handle_size_change"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      :title="dialog_title"
      :visible.sync="dialog_visible"
      width="700px"
    >
      <el-form
        :model="announcement_form"
        label-width="100px"
        ref="announcement_form"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model.trim="announcement_form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input v-model.trim="announcement_form.content" placeholder="请输入公告内容" type="textarea" rows="8" />
        </el-form-item>

        <el-form-item label="发布状态" prop="type">
          <el-radio-group v-model="announcement_form.type">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog_visible = false">取消</el-button>
        <el-button type="primary" @click="handle_submit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="查看公告"
      :visible.sync="view_visible"
      width="700px"
    >
      <div class="announcement-detail">
        <h2 style="text-align: center;">{{ view_data.title }}</h2>
        <div class="announcement-info" style="text-align: center; margin: 20px 0; color: #666;">
          发布人：{{ view_data.author }} | 发布时间：{{ view_data.publish_time }}
        </div>
        <div class="announcement-content" style="line-height: 1.8; white-space: pre-wrap;">{{ view_data.content }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="view_visible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import sysAnnouncementApi from '@/api/sys-announcement'
import sysUserApi from '@/api/sys-user'

export default {
  name: 'AnnouncementManagement',
  data() {
    return {
      loading: false,
      announcement_list: [],
      total: 0,
      page_num: 1,
      page_size: 10,
      search_form: {
        title: '',
        type: ''
      },
      dialog_visible: false,
      dialog_title: '',
      view_visible: false,
      announcement_form: {
        id: '',
        title: '',
        content: '',
        type: 1,
        status: 1
      },
      view_data: {},
      // 用于缓存用户信息，避免重复请求
      userMap: {}
    }
  },
  created() {
    this.get_list()
  },
  methods: {
    // 获取用户信息
    async getUserInfo(userId) {
      if (!userId) return '未知用户'
      
      // 如果缓存中有，直接返回
      if (this.userMap[userId]) {
        return this.userMap[userId]
      }
      
      try {
        const { data } = await sysUserApi.detail(userId)
        // 缓存用户信息
        this.userMap[userId] = data.username || '未知用户'
        return this.userMap[userId]
      } catch (error) {
        console.error('获取用户信息失败:', error)
        return '未知用户'
      }
    },
    
    // 获取公告列表
    async get_list() {
      this.loading = true
      try {
        const params = {
          page_num: this.page_num,
          page_size: this.page_size,
          ...this.search_form
        }
        const { data } = await sysAnnouncementApi.list(params)
        
        // 处理公告列表，添加用户名信息
        const records = data.records || []
        for (let record of records) {
          // 获取并设置用户名
          record.author = await this.getUserInfo(record.publisher_id)
        }
        
        this.announcement_list = records
        this.total = data.total
      } catch (error) {
        this.$message.error('获取公告列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handle_search() {
      this.page_num = 1
      this.get_list()
    },
    // 重置搜索条件
    handle_reset() {
      this.search_form = {
        title: '',
        type: ''
      }
      this.get_list()
    },
    
    // 新增
    handle_add() {
      this.dialog_title = '新增公告'
      this.announcement_form = {
        id: '',
        title: '',
        content: '',
        publishTime: null,
        type: 1,
        status: 1
      }
      this.dialog_visible = true
    },
    
    // 编辑
    handle_edit(row) {
      this.dialog_title = '编辑公告'
      // 创建副本以避免修改原始数据
      const formData = { ...row }
      // 确保publish_time字段正确设置
      formData.publish_time = row.publish_time || row.publishTime
      // 删除不需要提交的字段
      delete formData.author
      delete formData.publisher_id
      delete formData.publisherId
      delete formData.publishTime
      this.announcement_form = formData
      this.dialog_visible = true
    },
    
    // 查看
    async handle_view(row) {
      // 确保显示正确的用户名
      if (row.publisher_id && !row.author) {
        row.author = await this.getUserInfo(row.publisher_id)
      }
      this.view_data = { ...row }
      this.view_visible = true
    },
    
    // 删除
    async handle_delete(id) {
      this.$confirm('确定要删除此公告吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await sysAnnouncementApi.delete(id)
          this.$message.success('删除成功')
          this.get_list()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },
    
    // 提交表单
    async handle_submit() {
      try {
        // 准备提交数据
        const submitData = { ...this.announcement_form }
        
        // 自动设置发布人ID为当前登录用户ID
        // 从store中获取当前用户ID，如果没有则使用默认值1
        const currentUserId = this.$store.getters.userId || 1
        submitData.publisherId = currentUserId
        
        // 如果是发布状态且没有设置发布时间，设置为当前时间
        // 注意：后端期望的字段名是publish_time
       
          submitData.publish_time = new Date()
       
        // 删除不需要的publishTime字段
        delete submitData.publishTime
        
        // 删除不需要提交的字段
        delete submitData.author
        
        if (submitData.id) {
          await sysAnnouncementApi.update(submitData)
          this.$message.success('更新成功')
        } else {
          await sysAnnouncementApi.add(submitData)
          this.$message.success('创建成功')
        }
        this.dialog_visible = false
        this.get_list()
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    // 分页处理
    handle_current_change(val) {
      this.page_num = val
      this.get_list()
    },
    
    handle_size_change(val) {
      this.page_size = val
      this.page_num = 1
      this.get_list()
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.announcement-detail {
  padding: 20px 0;
}

.announcement-content {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}
</style>